package com.msb.controller;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sunpeng
 * @Date 2021-06-01 17:33
 */

/*
response
1.servletHttp
2.forward/redirect
3.view/modelAndView
4.json
*/

@Controller
public class ResponseController {

    @RequestMapping(value = "/request1", method = RequestMethod.GET)
    public String response1(){
        System.out.println("request1");
        return "success"; //配合视图解析器，跳转到web/success.jsp
        // 返回是string类型但没有此静态资源：404，web/string.jsp
        // 返回不是string类型：500，类型不匹配
    }

    /*
     * @ResponseBody
     * 1方法的返回值不在作为界面跳转依据,而已直接作为返回的数据
     * 2将方法的返回的数据自动使用ObjectMapper转换为JSON
     */
    @ResponseBody
    @RequestMapping(value = "/response2", method = RequestMethod.GET)
    public String response2(){
        System.out.println("response2");
        return "success"; //返回字符串success
        //可以返回任意类型，不做跳转
    }

    //请求转发
    @RequestMapping(value = "/forward")
    public String forward(){
        System.out.println("forward");
        return "forward:WEB-INF/jsp/success.jsp";
    }

    //重定向
    @RequestMapping(value = "/redirect")
    public String redirect(){
        System.out.println("redirect");
        return "redirect:index.jsp";
        //WEB-INF/jsp/success.jsp不行，必须给全路径，像视图层一样
    }

    //视图 请求转发/重定向
    @RequestMapping(value = "/view")
    public View viewFun(HttpServletRequest request){
        System.out.println("view");
        //View view = new InternalResourceView("/forwardPage.jsp");  //请求转发
        View view = new RedirectView(request.getContextPath() + "/redirectPage.jsp"); //重定向
        return view;
    }

    //视图 请求转发/重定向
    @RequestMapping(value = "/mv")
    public ModelAndView mvFun(HttpServletRequest request){
        System.out.println("view");
        ModelAndView mv = new ModelAndView();
        //请求转发
        mv.setViewName("forward:/forwardPage.jsp");
//        mv.setView(new InternalResourceView("/forwardPage.jsp"));
//        //重定向
//        mv.setViewName("redirect:/redirectPage.jsp");
//        mv.setView(new RedirectView(request.getContextPath() + "/redirectPage.jsp"));
        return mv;
    }

}
